package mvc.model {
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.loadingtypes.ImageItem;
	import br.com.stimuli.loading.loadingtypes.LoadingItem;

	import com.pblabs.engine.PBUtil;

	import flash.display.MovieClip;
	import flash.events.Event;

	import org.puremvc.as3.patterns.proxy.Proxy;

	public class ResourceProxy extends Proxy {
		public static const NAME:String = "ResourceProxy";

		public static var rootPath:String;

		private var loader:BulkLoader;

		public function ResourceProxy() {
			super(NAME);
			loader = new BulkLoader("loader");
			rootPath = "../resources/";
		}

		public function isLoaded(path:String):Boolean {
			if (loader.get(path))
				return true;
			else
				return false;
		}

		public function getMovieClip(path:String):MovieClip {
			var item:LoadingItem = loader.get(path);
			if (item == null) {
				throw new Error("The movie clip: " + path + " is not loaded");
			} else {
				return loader.getMovieClip(path);
			}
		}

		public function getResourceClass(path:String, className:String):Class {
			var item:ImageItem = loader.get(path) as ImageItem;
			if (item == null) {
				throw new Error("The resource: " + path + " is not loaded");
			} else {
				return item.getDefinitionByName(className) as Class;
			}
		}

		public function loadResource(path:String, onComplete:Function, onProgress:Function = null,
			onError:Function = null):void {
			loader.add(getAbsolutePath(path), {id: path});
			loader.get(path).addEventListener(Event.COMPLETE, onComplete, false, 0, true);
			if (onProgress != null)
				loader.get(path).addEventListener(Event.COMPLETE, onProgress, false, 0, true);
			if (onError != null)
				loader.get(path).addEventListener(Event.COMPLETE, onError, false, 0, true);
			loader.start();
		}

		public function loadStaticResources():void {

		}

		public function loadResources(path:Array, onComplete:Function, onProgress:Function = null,
			onError:Function = null):void {
			for each (var p:String in path) {
				loader.add(getAbsolutePath(p), {id: p});
			}
			loader.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
			if (onProgress != null)
				loader.addEventListener(Event.COMPLETE, onProgress, false, 0, true);
			if (onError != null)
				loader.addEventListener(Event.COMPLETE, onError, false, 0, true);
			loader.start();
		}

		private function getAbsolutePath(path:String):String {
			var r:String = PBUtil.trimFront(path, "/");
			r = rootPath + r;
			return r;
		}
	}
}
